package net.huashitong.ssydt.provider.pk.service;

import net.huashitong.ssydt.base.dao.LongMapper;
import net.huashitong.ssydt.base.service.AbstractLongService;
import net.huashitong.ssydt.pk.constant.PkConsts;
import net.huashitong.ssydt.pk.entity.SsPkGameRule;
import net.huashitong.ssydt.pk.entity.SsPkMyChallenge;
import net.huashitong.ssydt.provider.pk.mapper.SsPkMyChallengeMapper;
import net.huashitong.ssydt.provider.utils.date.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.12.11
 */
@Service
@Transactional
public class SsPkMyChallengeServiceImpl extends AbstractLongService<SsPkMyChallenge> implements SsPkMyChallengeService {

    private SsPkMyChallengeMapper mapper;

    private SsPkGameRuleService ssPkGameRuleService;

    @Autowired
    public SsPkMyChallengeServiceImpl(SsPkMyChallengeMapper mapper, SsPkGameRuleService ssPkGameRuleService) {
        this.mapper = mapper;
        this.ssPkGameRuleService = ssPkGameRuleService;
    }

    @Override
    protected LongMapper<SsPkMyChallenge> getLongMapper() {
        return this.mapper;
    }

    @Override
    public SsPkMyChallenge getAutoUpdateByUserId(String userId) {
        SsPkMyChallenge ssPkMyChallenge = mapper.getByUserId(userId);
        if (ssPkMyChallenge == null) {
            ssPkMyChallenge = new SsPkMyChallenge();
            ssPkMyChallenge.setUserId(userId);
            ssPkMyChallenge.setSynDate(DateUtils.getDate());
            setAutoUpdateInfo(ssPkMyChallenge);
            this.insert(ssPkMyChallenge);
        }
        String nowDate = DateUtils.getDate();
        if (!nowDate.equals(ssPkMyChallenge.getSynDate())) {
            setAutoUpdateInfo(ssPkMyChallenge);
            ssPkMyChallenge.setSynDate(nowDate);
            this.updateByPrimaryKeySelective(ssPkMyChallenge);
        }

        return ssPkMyChallenge;
    }

    /**
     * 设置每天自动更新的免费次数
     *
     * @param ssPkMyChallenge
     */
    private void setAutoUpdateInfo(SsPkMyChallenge ssPkMyChallenge) {
        SsPkGameRule ssPkGameRule = ssPkGameRuleService.getByType(PkConsts.RuleType.YMDX);
        ssPkMyChallenge.setYmdx(ssPkGameRule != null ? ssPkGameRule.getFreeTimes() : 0);
        ssPkGameRule = ssPkGameRuleService.getByType(PkConsts.RuleType.YZDD);
        ssPkMyChallenge.setYzdd(ssPkGameRule != null ? ssPkGameRule.getFreeTimes() : 0);
    }


}
